package com.gz.redis.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/redisTest")
public class RedisTestController {

    //注意:用jedis存的就用jedis取，早linux中redis存，就在linux中的redis取
    //否则会有序列化的错误，即linux中的值在客户端jedis取时有错误

    //装配RedisTemplate
    @Resource
    RedisTemplate redisTemplate;

    @RequestMapping("/t1")
    public String t1(){

//        Set keys = redisTemplate.keys("*");

        //设置值
        redisTemplate.opsForValue().set("game","LOL");

        //获取值
        String game = (String) redisTemplate.opsForValue().get("game");

        return game;
    }

    //编写方法,演示如何操作list,hash,set,zset
    @GetMapping("/t2")
    public String t2() {
        //list-存
        redisTemplate.opsForList().leftPush("books", "笑傲江湖");
        redisTemplate.opsForList().leftPush("books", "hello,java");

        //list-取出
        List books = redisTemplate.opsForList().range("books", 0, -1);
        String booksList = "";
        for (Object book : books) {
            System.out.println("book-->" + book.toString());
            booksList += book.toString() + " ";
        }
        //hash
        //redisTemplate.opsForHash()
        //set
        //redisTemplate.opsForSet()
        //zset
        //redisTemplate.opsForZSet()
        return booksList;
    }

    //编写一个方法,获取所有的key
    @GetMapping("/t3")
    public String t3() {
        Set keys = redisTemplate.keys("*");
        for (Object key : keys) {
            System.out.println("key--->" + key.toString());
        }
        return "OK";
    }


    //编写方法,获取通过客户端添加的数据-会出现异常
    //需要保持一致，比如RedisTemplate读取的数据,应当是RedisTemplate存放的数据
    @GetMapping("/t4")
    public String t4() {

        String val = (String) redisTemplate.opsForValue().get("book");

        System.out.println("val= " + val);

        return val;
    }

}
